package com.example.demo.handler;


import com.example.demo.exception.BusinessException;
import com.example.demo.result.ResponseResult;
import lombok.extern.slf4j.Slf4j;

import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wumin
 * @version 1.0
 * @Description: 全局异常处理
 * @date 2021/4/7 15:19
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 数据库操作异常
     *
     * @param e 异常
     */
    @ExceptionHandler(value = DataAccessException.class)
    @ResponseBody
    public ResponseResult<String> dataAccessException(DataAccessException e) {
        log.error(e.getMessage(), e);
        Throwable throwable = getThrowable(e);
        return ResponseResult.error("数据库异常：" + throwable.getMessage());
    }




    /**
     * 自定义业务异常
     *
     * @param e 异常
     */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public ResponseResult<String> businessException(BusinessException e) {
        log.error(e.getMessage(), e);
        return ResponseResult.error(e.getCode(), e.getMessage());
    }

    /**
     * 全局异常
     *
     * @param e 异常
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseResult<String> handleException(Exception e) {
        log.error(e.getMessage(), e);
        Throwable throwable = getThrowable(e);
        return ResponseResult.error("服务器异常：" + throwable.getMessage());
    }


    /**
     * @description 获取最里层异常
     * @author wumin
     * @date 2021-04-12 17:21
     * @param: throwable
     * @return: java.lang.Throwable
     */
    private Throwable getThrowable(Throwable throwable) {
        Throwable result = throwable;
        while (result.getCause() != null) {
            result = result.getCause();
        }

        return result;
    }
}
